package com.lenovo.mso2o.service;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Vibrator;
import android.support.annotation.Nullable;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.lenovo.framework.base.FBaseActivity;
import com.lenovo.framework.biz.ContextManager;
import com.lenovo.framework.service.LocationService;
import com.lenovo.mso2o.MSApplication;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.entity.Order;
import com.lenovo.mso2o.entity.g.AlarmTime;
import com.lenovo.mso2o.entity.g.AlarmTimeDao;
import com.lenovo.mso2o.entity.g.AutoSignOrder;
import com.lenovo.mso2o.entity.g.AutoSignOrderDao;
import com.lenovo.mso2o.ui.MainActivity;
import com.lenovo.mso2o.ui.fragment.AutoSignFragment;
import com.lenovo.mso2o.util.SendNotification;
import com.lenovo.mso2o.util.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import de.greenrobot.dao.query.QueryBuilder;
import rx.Scheduler;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by lenovo on 2016/3/8.
 */
public class AutoSignService extends Service implements LocationService.LocationSuccessListener {
    //逻辑：每隔x秒，遍历一次数据库
    private AutoSignOrder autoSignOrder;
    private AutoSignOrderDao autoSignOrderDao;
    private AlarmTimeDao alarmTimeDao;
    public static ArrayList<Order> mOrders;
    private static Scheduler.Worker worker;
    private ServiceConnection conn;
    private Intent bindIntent;
    public static LatLng mLatLng;
    private ArrayList<AutoSignOrder> forShowList;
    private Handler mHandler;
    public static final String OPEN_ORDER_AND_SIGN = "open_order_and_sign";
    private static volatile boolean bind = false;
    //worker auto sign duration, foreground 10s, background, 30s, sleep 500s
    private static int duration = -1;

    public static int getDuration(){
        return duration;
    }

    public static void setDurationIfChanged(int duration) {
        if(duration != AutoSignService.duration) {
            AutoSignService.duration = duration;
            Intent serviceIntent = new Intent(ContextManager.context(), AutoSignService.class);
            ContextManager.context().startService(serviceIntent);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        autoSignOrderDao = MSApplication.getDaoSession().getAutoSignOrderDao();
        alarmTimeDao = MSApplication.getDaoSession().getAlarmTimeDao();
        bindIntent = new Intent(AutoSignService.this, LocationService.class);
        conn = LocationService.connection(AutoSignService.this, bindIntent);
    }


    private void startTimer(int duration) {
        if(worker != null){
            worker.unsubscribe();
            worker = null;
        }
        worker = Schedulers.io().createWorker();
        worker.schedulePeriodically(new Action0() {
            @Override
            public void call() {
                /*
                if (MSApplication.isActivityVisible()) {
                    if (!bind && conn != null) {
                        bindService(bindIntent, conn, BIND_AUTO_CREATE);
                        bind = true;
                    }
                }
                */
                //若当前时间值大于预约时间则删除它
                alarmTimeDao.queryBuilder().where(AlarmTimeDao.Properties.Deadtime.lt(System.currentTimeMillis())).buildDelete().executeDeleteWithoutDetachingEntities();
                //每隔10秒钟查询一次表 AlarmTime, 从数据库中作判断：若是到场的单 时间值在介于两个时间值之间
                //则发通知响铃 同时删除该工单
                final List<AlarmTime> list = alarmTimeDao.queryBuilder().where(AlarmTimeDao.Properties.Pretime.lt(System.currentTimeMillis()), AlarmTimeDao.Properties.Deadtime.gt(System.currentTimeMillis())).list();
                if (list != null && list.size() > 0) {
                    for (AlarmTime alarmTime : list) {
                        final String ticketId = alarmTime.getTickedid();
                        final String alarmInfo = alarmTime.getAlarminfo();
                        AutoSignOrder signOrder_ = autoSignOrderDao.queryBuilder().where(AutoSignOrderDao.Properties.Ticketid.eq(ticketId)).unique();
                        if (signOrder_ != null && getString(R.string.reached).equals(signOrder_.getOrderStatus())) {
                            //发个通知
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    SendNotification.sendNotification(R.drawable.ic_launcher, "预约: " + alarmInfo, "工单编号为：" + ticketId, AutoSignService.this, true, ticketId.hashCode(), PendingIntent.FLAG_UPDATE_CURRENT, MainActivity.OPEN_FILTER);
                                    Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                                    vib.vibrate(5 * 1000);
                                }
                            });
                            //从库中删除
                            alarmTimeDao.delete(alarmTime);
                        }
                    }
                }
            }
        }, 5, duration == -1 ? 10 : duration, TimeUnit.SECONDS);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        autoSignOrderDao.deleteAll();
        if (mOrders != null && mOrders.size() > 0) {
            for (Order order : mOrders) {
                autoSignOrder = new AutoSignOrder();
                autoSignOrder.setProject(order.getProject());
                autoSignOrder.setItsmcode(order.getItsmcode());
                autoSignOrder.setTicketid(order.getTicketid());
                autoSignOrder.setTitle(order.getTitle());
                autoSignOrder.setCaddress(order.getCaddress());
                autoSignOrder.setPosition(order.getPosition());
                autoSignOrder.setPriority(order.getPriority());
                if (order.getShortcut() != null)
                    autoSignOrder.setOrderStatus(order.getShortcut().getName());
                autoSignOrderDao.insert(autoSignOrder);
            }
        }
        startTimer(duration);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        //if (subscriptions != null)
        //subscriptions.unsubscribe();
        if (conn != null) {
            if(bind) {
                try {
                    unbindService(conn);
                }catch (Exception e){}
                bind = false;
            }
            conn = null;
            bindIntent = null;
        }
        if(worker != null) {
            worker.unsubscribe();
            worker = null;
        }
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        if (conn != null) {
            if(bind) {
                try {
                    unbindService(conn);
                }catch (Exception e){}
                bind = false;
            }
        }
        //查询数据库
        if (location != null) {
            mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
            //查询自动签到数据库，看看有无需要自动签到的工单
            //如果签到的位置和当前位置在500m以内，则不去查数据库
            if(AutoSignFragment.signedLatLng != null){
                if(DistanceUtil.getDistance(mLatLng, AutoSignFragment.signedLatLng) > MSConstants.RADIS_MIN_SIGN){
                    //queryAutosignDB();
                }
            }else {
                //queryAutosignDB();
            }
        }
    }

    private void queryAutosignDB() {
        QueryBuilder qb = autoSignOrderDao.queryBuilder();
        qb.where(AutoSignOrderDao.Properties.OrderStatus.eq(getString(R.string.reached)));
        List<AutoSignOrder> signOrders = qb.list();
        forShowList = new ArrayList<>();
        if (signOrders != null && signOrders.size() > 0) {
            for (AutoSignOrder order : signOrders) {
                String position = order.getPosition();
                if (position != null) {
                    String[] latLngStr = position.split(":");
                    double lng = Double.valueOf(latLngStr[0]);
                    double lat = Double.valueOf(latLngStr[1]);
                    if (mLatLng != null) {
                        double distance = DistanceUtil.getDistance(new LatLng(lat, lng), mLatLng);
                        if (distance <= MSConstants.RADIS_MIN_SIGN) {//两点距离小于1000m
                            forShowList.add(order);
                        }
                    }
                }
            }
        }
        //如果forShowList中有数据，就要展示出来
        if (forShowList != null && forShowList.size() > 0) {
            AutoSignFragment.mSignOrders = forShowList;
            //判断当前应用是否在前台
            //若在前台：直接弹出Fragment
            //若不在前台：发一个通知
            if (MSApplication.isActivityVisible() && !AutoSignFragment.getAutoSignInstance().isResumed()) {
                List<Activity> activities = FBaseActivity.getActivites();
                if(activities.size() > 0) {
                    Activity curr = activities.get(activities.size() - 1);
                    if (curr instanceof MainActivity && ((MainActivity) curr).currIdx() == 1) {
                        Intent dialogIntent = new Intent(getBaseContext(), MainActivity.class);
                        dialogIntent.putExtra(MainActivity.OPEN_ORDER_SIGN, true);
                        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        getApplication().startActivity(dialogIntent);
                        return;
                    }
                }
            }
            //少于5分钟不提示签到
            if(System.currentTimeMillis() - AutoSignFragment.currentTime < 300*1000)
                return;
            //发一个通知吧
            if (mHandler == null) {
                mHandler = new Handler(getMainLooper());
            }
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    SendNotification.sendNotification(R.drawable.ic_launcher, "签到提醒", "您有可签到的工单，点击查看", AutoSignService.this, true, R.string.auto_sign_pls, PendingIntent.FLAG_UPDATE_CURRENT, MainActivity.OPEN_ORDER_SIGN);
                    Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                    vib.vibrate(5 * 1000);
                    AutoSignFragment.currentTime = System.currentTimeMillis();
                }
            });
        }
    }
}
